import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:shenling_logistics/pages/mine/index.dart';
import 'package:shenling_logistics/pages/notice/index.dart';
import 'package:shenling_logistics/pages/task/index.dart';
import 'package:shenling_logistics/utils/eventBus.dart';
import 'package:shenling_logistics/utils/token.dart';

class TabBarPage extends StatefulWidget {
  const TabBarPage({super.key});

  @override
  State<TabBarPage> createState() => _TabBarPageState();
}

class _TabBarPageState extends State<TabBarPage> {
  // 记录当前页面选中的索引
  int currentIndex = 0;
  //  底部TabBar数据
  List tabBarList = [
    {'title': '任务', 'default': 'assets/tabs/ic_tab_btn_task.svg'},
    {'title': '消息', 'default': 'assets/tabs/ic_tab_btn_mess_nor.svg'},
    {'title': '我的', 'default': 'assets/tabs/ic_tab_btn_mine_nor.svg'},
  ];

  @override
  void initState() {
    super.initState();
    // 用户一开始进入页面，就从本地获取token
    Future.delayed(Duration.zero, () async {
      await TokenManager().init();
    });

    // 注册登录失效事件，通知跳转到登录页
    eventBus.on<LogoutEvent>().listen((event) {
      // 跳转到登录页
      Navigator.pushNamed(context, '/login');
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: IndexedStack(
        index: currentIndex,
        children: [
          TaskPage(),
          NoticePage(),
          MinePage(currentIndex: currentIndex),
        ],
      ),
      bottomNavigationBar: BottomNavigationBar(
        backgroundColor: Colors.white,
        selectedItemColor: Colors.red,
        unselectedItemColor: Colors.grey,
        currentIndex: currentIndex,
        items: getBottomNavigationBarItem(),
        onTap: (value) {
          setState(() {
            currentIndex = value;
          });
        },
      ),
    );
  }

  // 抽取底部导航条item方法
  List<BottomNavigationBarItem> getBottomNavigationBarItem() {
    // 定义初始空列表
    List<BottomNavigationBarItem> tempList = [];
    for (var item in tabBarList) {
      tempList.add(
        BottomNavigationBarItem(
          label: item['title'],
          icon: SvgPicture.asset(
            item['default'],
            width: 30,
            height: 30,
            colorFilter: ColorFilter.mode(Colors.grey, BlendMode.srcIn),
          ),
          activeIcon: SvgPicture.asset(
            item['default'],
            width: 30,
            height: 30,
            colorFilter: ColorFilter.mode(Colors.red, BlendMode.srcIn),
          ),
        ),
      );
    }
    return tempList;
  }
}
